import config from 'config';
import { Application } from 'express';
import session, { Store } from 'express-session';

let store: Store;

if (process.env.NODE_ENV === 'production') {
  let redisClient = (require('redis')).createClient(
    config.get('redis.port'),
    config.get('redis.host')
  );
  store = new (require('connect-redis')(session))({ client: redisClient });
} else {
  store = new (require('express-mysql-session')(session))({
    user: config.get('sqlServer.user'),
    password: `${config.get('sqlServer.password')}`,
    database: 'jupiter_dev',
    host: config.get('sqlServer.host'),
  });
}

export default function addMiddlewars(app: Application) {
  app.use(session({
    secret: config.get('security.key'),
    resave: false,
    saveUninitialized: false,
    cookie: {
      maxAge: 60 * 60 * 24 * 30 * 1000, // 30 days
    },
    store,
  }));
}
